package cn.jinjimi.app;

import cn.jinjimi.domain.Dispatcher;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;

/**
 * Created by zhenhua on 16/7/8.
 */
public class DefaultDispatcher implements Dispatcher {

    private static volatile DefaultDispatcher mDefaultDispatcher = null;
    private static HashSet<Object> mCachedRegisters = new HashSet<>();

    public static Dispatcher get() {
        if (mDefaultDispatcher == null) {
            synchronized (DefaultDispatcher.class) {
                if (mDefaultDispatcher == null) {
                    mDefaultDispatcher = new DefaultDispatcher();
                }
            }
        }
        return mDefaultDispatcher;
    }

    @Override
    public void dispatch(Object object) {
        EventBus.getDefault().post(object);
    }

    @Override
    public void unregister(Object object) {
        mCachedRegisters.remove(object);
        EventBus.getDefault().unregister(object);
    }

    @Override
    public void register(Object object) {
        mCachedRegisters.add(object);
        EventBus.getDefault().register(object);
    }

    @Override
    public void onDestroy() {
        //clear objects unregistered yet.
        for (Object o : mCachedRegisters) {
            if (o != null) {
                EventBus.getDefault().unregister(o);
            }
        }
    }
}
